<template>
  <div class="lineColorsContainer">
    <!-- Canvas 画布 -->
    <canvas ref="canvas" width="255px" height="60px"></canvas>
    <!-- 滑动条 -->
    <div class="customSlider">
      <el-slider
        :min="sliderConfig.min"
        :max="sliderConfig.max"
        v-model="lineWidth"
        @change="(size) => drawLine(size, props.color)"
      ></el-slider>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch, PropType, reactive, nextTick } from 'vue';
import { newSizeData } from '../utils/sizeColor';
import { cloneDeep } from 'lodash';

const props = defineProps({
  color: {
    type: String as PropType<string>,
    default: '#ff6a33', // 默认颜色
  },
  size: {
    type: Number,
    default: null, // 默认大小
  },
});

// 使用 ref 定义画布和线条粗细
const canvas = ref<HTMLCanvasElement | null>(null);
const lineWidth = ref<any>(null);
const deep = cloneDeep(newSizeData);
const sliderConfig = reactive({
  min: deep[0],
  max: deep.pop(),
});

const emits = defineEmits(['ok']);

// 尺寸发生改变 重新绘制贝塞尔曲线，和发送emit
// 这怎么props更新也会触发啊 吐了
const drawLine = (width: number, color: string) => {
  lineWidth.value = width;
  // console.log('执行=====================> xxxxxxxxxxxx =============>', width);
  const ctx = canvas.value?.getContext('2d');
  // console.log('ctx ====> ', ctx)
  if (!ctx) return;
  // 清除画布
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  // 绘制 S 形曲线
  ctx.beginPath();
  ctx.moveTo(20, 30); // 起点
  ctx.bezierCurveTo(80, 0, 160, 70, 240, 30); // 使用三次贝塞尔曲线形成 "S" 形
  ctx.lineCap = 'round'; // 设置两端为圆角
  ctx.lineWidth = width;
  ctx.strokeStyle = color;
  ctx.stroke();
  //
  emits('ok', width);
};

// 监听size和color变化
watch(
  [() => props.size, () => props.color],
  async ([newSize, newColor]) => {
    await nextTick();
    // console.log('newSize ====> ', newSize)
    // console.log('newColor ====> ', newColor)
    if (newSize || newColor) {
      drawLine(newSize, newColor);
    }
  },
  {
    immediate: true,
    deep: true,
  },
);
</script>

<style lang="scss">
.lineColorsContainer {
  width: 100%;
  // border: 1px solid red;

  canvas {
    // border: 1px solid #ddd
  }

  .customSlider {
    // border: 1px solid red;
    padding: 0 15px;

    .el-slider__runway {
      height: 20px;
      border-radius: 60px;

      .el-slider__bar {
        height: 20px;
        border-radius: 60px 0 0 60px;
        background: #e4e7ed;
      }

      .el-slider__button-wrapper {
        width: 20px;
        height: 20px;
        top: 0;
        display: flex;
        // background: #d8d8d8;
        background: #e4e7ed;
        // border: 1px solid red;
      }

      .el-slider__button {
        box-sizing: content-box;
        width: 16px;
        height: 16px;
        background: #ffffff;
        border-color: #ffffff;
      }
    }
  }
}
</style>
